package com.hnucm.c201901020241.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.TextView;

import com.app.hubert.guide.NewbieGuide;
import com.app.hubert.guide.core.Controller;
import com.app.hubert.guide.listener.OnGuideChangedListener;
import com.app.hubert.guide.listener.OnPageChangedListener;
import com.app.hubert.guide.model.GuidePage;
import com.app.hubert.guide.model.HighLight;
import com.bumptech.glide.Glide;
import com.hnucm.c201901020241.R;
import com.hnucm.c201901020241.discuss.Discuss_post_information;
import com.hnucm.c201901020241.discuss.Disscuss_item;
import com.hnucm.c201901020241.pojo.CommentsReceived;
import com.hnucm.c201901020241.pojo.Content;
import com.hnucm.c201901020241.pojo.DongTai;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

public class DongtaiFragment extends Fragment {
    List<DongTai>dongTaiList;
    MyAdapter myAdapter;
    RecyclerView recyclerView;
    String information,account,name_floor;
    Boolean isselect;
    private String TAG = DongtaiFragment.class.getSimpleName();
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        SharedPreferences sharedPreferences=getActivity().getSharedPreferences("user",getActivity().MODE_MULTI_PROCESS);
        account=sharedPreferences.getString("account","");
        name_floor=sharedPreferences.getString("name","");
        return inflater.inflate(R.layout.fragment_dongtai, container, false);
    }
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser) {
//可见时执行的操作
//            点击了当前的页面
            isselect=true;
            Log.i("main1","是我");
        }else{
            isselect=false;
            Log.i("main1","不是我");
//不可见时执行的操作
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        dongTaiList=new ArrayList<>();
        recyclerView=getActivity().findViewById(R.id.recyclerView);
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("user",getActivity().MODE_MULTI_PROCESS);
        String account =  sharedPreferences.getString("account","fault");
        x.Ext.init(getActivity().getApplication());
        RequestParams requestParams = new RequestParams("http://121.4.27.254:8090/queryCommentsReceivedtList?");
        requestParams.addQueryStringParameter("account",account);
        myAdapter=new MyAdapter();
        x.http().get(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.i("DontTai",result);
                try {
                    JSONArray jsonArray=new JSONArray(result);
                    for(int i=0;i<jsonArray.length();i++){
                        DongTai dongTai=new DongTai();
                        JSONObject jsonObject=jsonArray.getJSONObject(i);
                        dongTai.setAccount(jsonObject.getString("account"));
                        dongTai.setName(jsonObject.getString("name"));
                        dongTai.setTime_floor(jsonObject.getString("time_floor"));
                        dongTai.setComments(jsonObject.getInt("comments"));
                        dongTai.setInformation(jsonObject.getString("information"));
                        dongTai.setTitle_discuss(jsonObject.getString("title_discuss"));
                        dongTai.setBase64(jsonObject.getString("base64"));
                        dongTai.setName_floor(jsonObject.getString("name_floor"));
                        dongTai.setBase64_floor(jsonObject.getString("base64_floor"));
                        dongTai.setTime(jsonObject.getString("time"));
                        dongTai.setMinformation(jsonObject.getString("minformation"));
                        dongTai.setTitle(jsonObject.getString("title"));
                        dongTaiList.add(dongTai);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                recyclerView.setAdapter(myAdapter);
                recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });



//        刷新
        RefreshLayout refreshLayout = (RefreshLayout)getActivity().findViewById(R.id.SmartRefreshLayout2);
        refreshLayout.setRefreshHeader(new ClassicsHeader(getActivity()));
        refreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()));
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                Log.i("DongtaiFragment","进入了上拉加载");
                refreshLayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });

//        刷新后模拟重新获得数据
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                dongTaiList.clear();
                Log.i("DongtaiFragment","进入了下拉刷新");
                x.Ext.init(getActivity().getApplication());
                RequestParams requestParams = new RequestParams("http://121.4.27.254:8090/queryCommentsReceivedtList?");
                requestParams.addQueryStringParameter("account",account);
                x.http().get(requestParams, new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        dongTaiList.clear();
                        Log.i("DontTai",result);
                        try {
                            JSONArray jsonArray=new JSONArray(result);
                            for(int i=0;i<jsonArray.length();i++){
                                DongTai dongTai=new DongTai();
                                JSONObject jsonObject=jsonArray.getJSONObject(i);
                                dongTai.setName(jsonObject.getString("name"));
                                dongTai.setTime_floor(jsonObject.getString("time_floor"));
                                dongTai.setComments(jsonObject.getInt("comments"));
                                dongTai.setName_floor(jsonObject.getString("name_floor"));
                                dongTai.setAccount(jsonObject.getString("account"));
                                dongTai.setInformation(jsonObject.getString("information"));
                                dongTai.setTitle_discuss(jsonObject.getString("title_discuss"));
                                dongTai.setBase64(jsonObject.getString("base64"));
                                dongTai.setBase64_floor(jsonObject.getString("base64_floor"));
                                dongTai.setTime(jsonObject.getString("time"));
                                dongTai.setTitle(jsonObject.getString("title"));
                                dongTaiList.add(dongTai);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        myAdapter.notifyDataSetChanged();
                        refreshLayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });

            }
        });
        SharedPreferences.Editor editor=sharedPreferences.edit();
        editor.putBoolean("init1",false);
        editor.putBoolean("init2",true);
        editor.putBoolean("init3",true);
        editor.putBoolean("init4",true);
        editor.commit();
        Boolean init=sharedPreferences.getBoolean("init3",false);
        Boolean isfirst=sharedPreferences.getBoolean("isfirst3",false);
        if(init&&!isfirst&&isselect){
            init_NewbieGuide();
            editor.putBoolean("isfirst3",true);
            editor.commit();
        }
    }

    private void init_NewbieGuide() {
        Log.i("main1","3进来了");
        Animation enterAnimation = new AlphaAnimation(0f, 1f);
        enterAnimation.setDuration(600);
        enterAnimation.setFillAfter(true);

        Animation exitAnimation = new AlphaAnimation(1f, 0f);
        exitAnimation.setDuration(600);
        exitAnimation.setFillAfter(true);

        NewbieGuide.with(this)
                .setLabel("DongtaiFragment")//设置引导层标示区分不同引导层，必传！否则报错
                .setShowCounts(1)
                .setOnGuideChangedListener(new OnGuideChangedListener() {//引导层显示监听
                    @Override
                    public void onShowed(Controller controller) {
                        Log.e(TAG, "NewbieGuide onShowed: ");
                        //引导层显示
                    }

                    @Override
                    public void onRemoved(Controller controller) {//引导层隐藏监听
                        Log.e(TAG, "NewbieGuide  onRemoved: ");
                        //引导层消失（多页切换不会触发）
                    }
                })
                .setOnPageChangedListener(new OnPageChangedListener() {//引导页切换监听
                    @Override
                    public void onPageChanged(int page) {
                        Log.e(TAG, "NewbieGuide  onPageChanged: " + page);
                        //引导页切换，page为当前页位置，从0开始
                    }
                })
                .alwaysShow(true)//是否每次都显示引导层，默认false，只显示一次
                /**
                 * 添加引导页一
                 */
                .addGuidePage(//添加一页引导页
                        GuidePage.newInstance()//创建一个实例
                                .addHighLight(getActivity().findViewById(R.id.constraintLayout8))//添加高亮的view
                                .addHighLight(getActivity().findViewById(R.id.constraintLayout8), HighLight.Shape.RECTANGLE)
                                .setLayoutRes(R.layout.dongtaifragment_style)//设置引导页布局
                                .setEnterAnimation(enterAnimation)//进入动画
                                .setExitAnimation(exitAnimation)//退出动画*/
                )


                /**
                 * 展示
                 */
                .show();//显示引导层(至少需要一页引导页才能显示)
    }

    public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
        public void freshAdapter(){
            notifyDataSetChanged();
        }
        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.comments_received_item, parent, false);
            MyViewHolder myViewHolder = new MyViewHolder(view);
            return myViewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
            Log.i("DongTai", String.valueOf(position));
            holder.nameTv.setText(dongTaiList.get(position).getName_floor());
            holder.timeTv.setText(dongTaiList.get(position).getTime_floor());
            holder.inforTv.setText(dongTaiList.get(position).getInformation());
            holder.titleTv.setText(dongTaiList.get(position).getTitle_discuss());
            holder.title2Tv.setText(dongTaiList.get(position).getTitle());
            holder.commentsTv.setText((dongTaiList.get(position).getComments())+"");

            byte[] imageBytes = Base64.decode(dongTaiList.get(position).getBase64_floor(), Base64.DEFAULT);
            Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
            holder.imageView.setImageBitmap(decodedImage);


            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//单击点开帖子,这里的时间需要传的是帖子建好的时间
                    Intent intent=new Intent(getActivity(), Discuss_post_information.class);
                    intent.putExtra("title_discuss",dongTaiList.get(position).getTitle_discuss());
                    intent.putExtra("name",dongTaiList.get(position).getName());
                    intent.putExtra("time",dongTaiList.get(position).getTime());
                    intent.putExtra("mainInformation",dongTaiList.get(position).getMinformation());
                    intent.putExtra("base64",dongTaiList.get(position).getBase64());
                    intent.putExtra("account",account);
                    startActivity(intent);
                }
            });
        }

        @Override
        public int getItemCount() {
            return dongTaiList.size();
        }
    }


    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView nameTv,timeTv,inforTv,titleTv,commentsTv,title2Tv;
        ImageView imageView;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.imageView12);
            nameTv=itemView.findViewById(R.id.textView38);
            timeTv=itemView.findViewById(R.id.textView40);
            inforTv=itemView.findViewById(R.id.textView41);
            titleTv=itemView.findViewById(R.id.textView43);
            commentsTv=itemView.findViewById(R.id.textView42);
            title2Tv=itemView.findViewById(R.id.textView45);
        }
    }
}